package com.jhws.business.local.service;

import com.alibaba.fastjson.JSON;
import com.jhws.business.local.bo.LocalConstant;
import com.jhws.common.base.bo.JsonRespData;
import com.jhws.core.db.BaseDao;
import com.jhws.sys.appUser.bo.TblSipAcountBindings;
import com.jhws.util.LogHelper;
import com.jhws.util.net.JhHttpClient;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Service
public class SipAcountBindingService {
    @Resource
    private BaseDao BaseDao;

    public void saveSipAcountBinding(TblSipAcountBindings sipAcountBindings) {
        sipAcountBindings.setIsSynch(LocalConstant.SYNCH_STATE_YES);
        BaseDao.saveOrUpdate(sipAcountBindings);
    }

    public void deleteSipAcountBinding(TblSipAcountBindings sipAcountBindings) throws Exception {
        BaseDao.delete(sipAcountBindings);
    }

    public List<TblSipAcountBindings> findTblSipAcountBindingWhere(String whereStr) throws Exception {
        return BaseDao.findList("from TblSipAcountBindings " + whereStr);
    }

    public void mergeSipAcount(String serverUrl, String commCode, Map<String, String> headers) throws Exception {
        List<TblSipAcountBindings> list = findTblSipAcountBindingWhere("where is_synch != '" + LocalConstant.SYNCH_STATE_YES + "' and binding like '" + commCode + "%'");
        if (list == null || list.isEmpty()) {
            return;
        }
        JhHttpClient hp = new JhHttpClient();
        for (TblSipAcountBindings sipAcountBindings : list) {
            String s = hp.postJson(serverUrl + "api/localSynch/sipAcountBinding/acountBindings", JSON.toJSONString(sipAcountBindings), headers);

            LogHelper.e("--------------------->      " + s);
            try {
                JsonRespData respData = JSON.parseObject(s, JsonRespData.class);
                if (respData.ret_code > 0) {
                    if (sipAcountBindings.getIsSynch() == LocalConstant.SYNCH_STATE_NO) {
                        saveSipAcountBinding(sipAcountBindings);
                    } else if (sipAcountBindings.getIsSynch() == LocalConstant.SYNCH_STATE_DEL) {
                        deleteSipAcountBinding(sipAcountBindings);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
